package yunplus.io.hchome.display.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import yunplus.io.hchome.R;
import yunplus.io.hchome.display.utils.ToastUtils;
import yunplus.io.hchome.display.view.ICheckVersionView;
import yunplus.io.hchome.display.view.ILoginView;
import yunplus.io.hchome.display.view.IWebAppView;
import yunplus.io.hchome.display.widget.FpmWebViewHandler;
import yunplus.io.hchome.display.widget.PreviewWebview;
import yunplus.io.hchome.model.api.FPM;
import yunplus.io.hchome.presenter.contract.ICheckVersionPresenter;
import yunplus.io.hchome.presenter.contract.ILaunchPresenter;
import yunplus.io.hchome.presenter.contract.IWebappPresenter;
import yunplus.io.hchome.presenter.implement.CheckVersionPresenter;
import yunplus.io.hchome.presenter.implement.WebappPresenter;
import yunplus.io.hchome.utils.HandlerUtils;

import static java.lang.System.exit;


public class WebviewActivity extends BaseActivity implements IWebAppView, ICheckVersionView{

    //------------------ private const define ----------------------
    private static final String TAG = "WebviewActivity";

    //------------------ control define ----------------------------

    @BindView(R.id.webview)
    PreviewWebview _mWebview;

    ProgressDialog _mProgressDialog;

    ProgressDialog _mLoadingDialog;

    AlertDialog.Builder _mAlertDialog;

    AlertDialog.Builder _mLogoutAlertDialog;

    AlertDialog.Builder _mLoadErrorAlertDialog;

    //------------------- presenter define --------------------------

    IWebappPresenter _mWebappPresenter;

    ICheckVersionPresenter _mCheckVersionPresenter;

    //------------------ var define ---------------------------------

    String _mDomain;

    boolean _isLan;

    String _mSavePath;

    JSONObject _user;

    String _mCurrentUrl;

    Pattern _mURLPattern = Pattern.compile("^(file:\\/\\/)[^\\s]+#\\/tabs\\/\\w+$");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview);

        ButterKnife.bind(this);

        _mWebappPresenter = new WebappPresenter(this, this);

        _mCheckVersionPresenter = new CheckVersionPresenter(this, this);

//        //get the domain
        _mDomain = getIntent().getStringExtra(IWebAppView.INTENT_EXTRA_KEY_DOMAIN);
        _isLan = getIntent().getBooleanExtra(IWebAppView.INTENT_EXTRA_KEY_LAN, false);
        if(_mDomain != null){
            Log.d(TAG, "get domain:" + _mDomain);
        }
        Log.d(TAG, "get domain:" + _mDomain);

        _mWebview.addJavascriptInterface(this, "FPM");

        //bind handler
        bindWebViewHandler();

        _mWebappPresenter.load();

        //checkversion
        _mCheckVersionPresenter.checkVersion("21ccf6e7112469053d4aa7d6ca47187f");
    }

    void bindWebViewHandler(){
        _mWebview.setHandler(new FpmWebViewHandler() {
            @Override
            public void error() {

            }

            @Override
            public void error(int code) {
                ToastUtils.with(WebviewActivity.this).show("加载失败");
                //弹出对话框，重新输入，或者刷新
                _mLoadErrorAlertDialog = new AlertDialog.Builder(WebviewActivity.this);
                _mLoadErrorAlertDialog.setTitle("提示")
                        .setMessage("页面加载失败!点击返回重新输入域名或刷新重试?")
                        .setCancelable(false)
                        .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //删除domain
                                _mWebappPresenter.logout();
                            }
                        })
                        .setNegativeButton("刷新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                _mWebview.reload();
                            }
                        })
                        .show();

            }

            @Override
            public void done() {
                if(_mLoadingDialog != null && _mLoadingDialog.isShowing()){
                    _mLoadingDialog.dismiss();
                }
            }

            @Override
            public void start() {
                _mLoadingDialog = new ProgressDialog(WebviewActivity.this);
                _mLoadingDialog.setMessage("正在加载...请稍后");
//                _mLoadingDialog.setCancelable(false);
                _mLoadingDialog.show();
            }
        });
    }
    void openApp(final String domain){
        HandlerUtils.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "openAPP : " + domain);
                _mWebview.loadUrl("file:///android_asset/index.html");
            }
        }, 300);
    }

    //FPM.jsLogout();
    @JavascriptInterface
    public void jsLogout(){

        _mLogoutAlertDialog = new AlertDialog.Builder(this);
        _mLogoutAlertDialog.setTitle("提示")
                .setMessage("是否确认登出?")
                .setCancelable(false)
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        _mWebappPresenter.logout();
                    }
                })
                .setNegativeButton("否",null)
                .show();
    }

    //FPM.jsLogout();
    @JavascriptInterface
    public String jsLoad() {
        if(null != _user){
            if(_isLan){
                _user.put("domain", ILaunchPresenter.LAN_DOMAIN);
            }
            return _user.toJSONString();
        }
        return "{}";
    }

    /**
     * 用于页面跳转
     * @param page
     */
    @JavascriptInterface
    public boolean forwardWithoutArgs(String page) {
        Class clz = null;
        try {
            clz = Class.forName("yunplus.io.hchome.display.activity." + page + "Activity");
        } catch (ClassNotFoundException e) {
            return false;
        }
        Intent intent = new Intent(this, clz);
        startActivity(intent);
        return true;
    }
    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (isExit == false) {
            isExit = true; // 准备退出
            ToastUtils.with(this).show("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            this.finish();
            exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        _mWebview.runJS("resetTimer();");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop");
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        _mWebview.runJS("stopTimer();");
    }

    @Override
    public void onBackPressed() {
        if (_mWebview.canGoBack()) {
            _mCurrentUrl = _mWebview.getUrl();
            Matcher matcher = _mURLPattern.matcher(_mCurrentUrl);
            // 字符串是否与正则表达式相匹配
            boolean rs = matcher.matches();
            if(rs){
                exitBy2Click();
            }else{
                _mWebview.runJS("goBack();");
            }

        } else {
            exitBy2Click();
        }
    }

    @Override
    public void logout() {
        startActivity(new Intent(this,LoginActivity.class));
        finish();
    }

    @Override
    public void onLoaded(@Nullable JSONObject user) {
        this._user = user;
        openApp(_mDomain);
    }

    @Override
    public void onLoaded() {
        openApp(_mDomain);
    }

    @Override
    public void onStartCheck() {
        Log.i(TAG, "开始检查更新");
    }

    @Override
    public void onFinishCheck(final JSONObject data) {

        Log.e(TAG, data.toJSONString());
        _mAlertDialog = new  AlertDialog.Builder(this);
        _mAlertDialog.setTitle("发现新版本 V" + data.getString("versionShort"))
                .setMessage( data.getString("changelog") + "\n\n是否前往更新？")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        _mSavePath = Environment.getExternalStorageDirectory() + "/" + data.getString("name") + data.getString("versionShort") + ".apk";
                        _mCheckVersionPresenter.updateVersion(data.getString("direct_install_url"), _mSavePath);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onFinishCheck() {
        //未检测到新版本
        Log.e(TAG, "onFinishCheck 未检测到新版本");
    }

    @Override
    public void onCheckError(String error) {
        ToastUtils.with(this).show("检查版本错误！\n" + error);
    }

    @Override
    public void onUpdateError(String error) {
        ToastUtils.with(this).show("版本更新错误！\n" + error);
    }

    @Override
    public void onStartUpdate() {

        _mProgressDialog = new ProgressDialog(this);
        _mProgressDialog.setMessage("正在下载...请稍后");
        _mProgressDialog.setCancelable(false);
        _mProgressDialog.show();

    }

    @Override
    public void onFinishUpdate() {
        _mProgressDialog.dismiss();
        _mCheckVersionPresenter.installVersion(_mSavePath);
    }
}
